import json

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from admins.models import TUser
from booksBorrow.views import commonList
from cloudLibraryDjango import common
from newbooksrecd.models import TBook


def getList(request):
    userName = request.session.get("user_name")
    userRole = request.session.get('user_role')
    return render(request, 'booksRecding/list.html', locals())


def list(request):
    # 表格要展现的数据
    status = ['1', '2']
    books = TBook.objects.filter(book_status__in=status)
    # 处理成LayUi官方文档的格式
    lis = commonList(books)

    res = common.getPageData(request, books, lis)
    result = common.getResult(books.count(), res)

    return HttpResponse(json.dumps(result))


def searchList(request):
    # 表格要展现的数据
    status = ['1', '2']
    books = TBook.objects.filter(book_status__in=status)

    bookName = request.GET.get("bookName")
    if bookName:
        books = books.filter(book_name=bookName)

    userName = request.GET.get("userName")
    if userName:
        users = TUser.objects.filter(user_name=userName)
        userIds = []
        for user in users:
            userIds.append(user.user_id)
        books = books.filter(book_borrower__in=userIds)

    res = commonList(books)

    # 放在一个列表里
    result = common.getResult(books.count(), res)
    return JsonResponse(result)


def edit(request):
    if request.POST:
        bookId = request.POST.get("bookId")
        if bookId is None:
            result = {"code": 1, "msg": "请选择要修改的数据"}
            return JsonResponse(result)
        bookStatus = request.POST.get("bookStatus")

        book = TBook.objects.get(book_id=bookId)

        if bookStatus:
            book.book_status = bookStatus

        book.save()
        result = {"code": 0, "msg": "归还成功"}
        return JsonResponse(result)

    result = {"code": 1, "msg": "归还失败"}
    return JsonResponse(result)
